#include "linkstack.h"
#include <stdlib.h>
#include <string.h>
#include "linklist.h"
#include "stdio.h"

typedef struct _tag_LinkStackNode _LinkStackNode;
struct _tag_LinkStackNode{
    LinkListNode node;
    void *data;
};

LinkStack* LinkStack_Create(){
    LinkList *list = LinkList_Create();
    return list;
}
void LinkStack_Destroy(LinkStack* stack){
    LinkStack_Clear(stack);
    LinkList_Destory(stack);
}
void LinkStack_Clear(LinkStack* stack){
    if(stack==NULL){
        perror("stack can not be null");
        return ;
    }
    while(LinkList_Length(stack)>0){
        LinkStack_Pop(stack);
    }
    LinkList_Clear(stack);
}

int LinkStack_Push(LinkStack* stack, void* item){
    if(stack==NULL){
        perror("stack can not be null");
        return -1;
    }
    _LinkStackNode* sn=(_LinkStackNode*)malloc(sizeof (_LinkStackNode));
    sn->data=item;
    int code = LinkList_Insert(stack,(LinkListNode*)sn,0);
    if(code!=0){
        if(sn!=NULL){
            free(sn);
        }
        return code;
    }
    return 0;

}

void* LinkStack_Pop(LinkStack* stack){
    if(stack==NULL){
        perror("stack can not be null");
        return NULL;
    }
    LinkListNode *last = LinkList_Delete((LinkList*)stack,0);
    if(last!=NULL){
        _LinkStackNode* sn=(_LinkStackNode*)last;
        void*d=sn->data;
        free(sn);
        return d;
    }
    return NULL;
}

void* LinkStack_Top(LinkStack* stack){
    if(stack==NULL){
        perror("stack can not be null");
        return NULL;
    }
    if(LinkStack_Size(stack)==0){
        return NULL;
    }
    LinkListNode *last = LinkList_Get((LinkList*)stack,0);
    if(last!=NULL){
        _LinkStackNode* sn=(_LinkStackNode*)last;
        void*d=sn->data;
        return d;
    }
    return NULL;
}
int LinkStack_Size(LinkStack* stack){
    if(stack==NULL){
        perror("stack can not be null");
        return -1;
    }
    return LinkList_Length((LinkList*)stack);
}
